<?php

namespace IDock\Insurance\DBIC\Response;

use IDock\Http\Response;
use IDock\IDock\IDockEnums;
use IDock\Insurance\DBIC\DBICEnums;
use IDock\Printer\NonCar\NonCarInquiryPrinter;
use IDock\Printer\NonCar\NonCarInquirySinglePrinter;
use IDock\Printer\Premium\PremiumBIPrinter;
use IDock\Printer\Premium\PremiumCoveragePrinter;
use IDock\Printer\Premium\PremiumInquiryPrinter;
use IDock\Printer\SpecialClausesPrinter;

class PremiumInquiryResponse extends AllDBICResponse
{

    /**
     * @var PremiumInquiryPrinter $printer
     * @var  $printer
     */
    public $printer = PremiumInquiryPrinter::class;

    protected $records = [];

    protected $result = [];

    public $planCode = '';

    public $productCode = '';

    public $insuredNum = 1;

    public function resolve(): Response
    {
        $body = $this->getBody();
        $body = json_decode($body, true);

        if ($this->printer) {
            $this->printer = new $this->printer;
        }

        $responseCode = $body['responseCode'] ?? '0';

        $errorMsg = $body['errorMsg'] ?? '';

        if ($responseCode != '1') {
            //重复投保
            $this->repeat($errorMsg);
            return $this;
        }
        $this->setBody($body ?? []);

        $this->result = $this->getBody()['result'] ?? [];
        $this->records = $this->result['data']['records'] ?? [];

        if ($this->BiRepeat()) {
            return $this;
        }

        return $this;
    }

    public function printerInit(): Response
    {
        if (!$this->printer->success) {
            return $this;
        }
        //询价流程号
        $this->printer->argc['calculateNo'] = $this->getRecords(0)['calculateNo'] ?? '';

        //车船税
        if ($carShipTax = $this->getRecords(0)['carShipTax'] ?? '') {
            $this->printer->carTaxPrinter->carShipTax = $carShipTax['sumTax'] ?? '';
            $this->printer->carTaxPrinter->overdue = $carShipTax['sumOverrdue'] ?? '';
            $this->printer->carTaxPrinter->payBackTax = $carShipTax['sumTaxDefault'] ?? '';
            $this->printer->carTaxPrinter->thisYearTax = $carShipTax['annualTaxDue'] ?? '';
        }
        //商业险平台信息
        $biQueryInfo = $this->getRecords(0)['biQueryInfo'] ?? [];

        //交强险平台信息
        $ciQueryInfo = $this->getRecords(0)['ciQueryInfo'] ?? [];

        //商业险
        if ($biData = $this->getRecords(0)['premiumBi'] ?? []) {
            $this->printer->biPremiumPrinter = new PremiumBIPrinter();
            $this->printer->biPremiumPrinter->biPremium = $biData['sumPremium'] ?? '';
            $this->printer->biPremiumPrinter->biBasePremium = $biData['sumBenchmarkPremium'] ?? '';
            $this->printer->biPremiumPrinter->biDiscount = $biData['discount'] ?? '';
            $this->printer->biInquiryNo = $biQueryInfo['querySequenceNo'] ?? '';

            $this->printer->ncdFactor = $biData['claimAdjustValue'] ?? '';

            //商业险系数
            $this->printer->premiumFactorPrinter->VCIFactorAppend('无赔款优待系数', 'ncdRate', $biData['claimAdjustValue'] ?? '');
            $this->printer->premiumFactorPrinter->VCIFactorAppend('交通违法系数', 'peccancyAdjustValue', $biData['peccancyAdjustValue'] ?? '');
            $this->printer->premiumFactorPrinter->VCIFactorAppend('短期费率', 'shortRate', $biData['shortRate'] ?? '');
            $this->printer->premiumFactorPrinter->VCIFactorAppend('连续承保年数', 'insureYears', $biData['insureYears'] ?? '');
            $this->printer->premiumFactorPrinter->VCIFactorAppend('连续承保期间出险次数', 'claimTimes', $biData['claimTimes'] ?? '');
            $this->printer->premiumFactorPrinter->VCIFactorAppend('无赔优系数级别', 'claimAdjustLevel', $biData['claimAdjustLevel'] ?? '');
            $this->printer->premiumFactorPrinter->VCIFactorAppend('商业险业务板块类型', 'ilogbusinesstypebi', $biData['ilogbusinesstypebi'] ?? '');
            //商业忠诚度
            if ($biQueryInfo['newVehicleFlag'] ?? '') {
                $this->printer->premiumFactorPrinter->VCIFactorAppend('商业险忠诚度', 'BIRenewalType', '新');
            } else {
                if (strlen($biQueryInfo['renewalFlag'] ?? '')) {
                    $this->printer->premiumFactorPrinter->VCIFactorAppend('商业险忠诚度', 'BIRenewalType', $biQueryInfo['renewalFlag'] ? '转' : '续');
                }
            }
        }

        //交强险
        if ($ciData = $this->getRecords(0)['premiumCi'] ?? []) {
            $this->printer->ciPremiumPrinter->ciPremium = $ciData['standardPremium'] ?? '';
            $this->printer->ciPremiumPrinter->ciBasePremium = $ciData['basedPremium'] ?? '';
            $this->printer->ciPremiumPrinter->ciDiscount = $ciData['discount'] ?? '';
            $this->printer->ciInquiryNo = $ciQueryInfo['querySequenceNo'] ?? '';

            $this->printer->premiumFactorPrinter->TCIFactorAppend('理赔调整系数', 'claimAdjustValue', $ciData['claimAdjustValue'] ?? '');
            $this->printer->premiumFactorPrinter->TCIFactorAppend('违法浮动原因代码', 'peccancyAdjustReason', $ciData['peccancyAdjustReason'] ?? '');
            $this->printer->premiumFactorPrinter->TCIFactorAppend('违法调整系数', 'peccancyAdjustValue', $ciData['peccancyAdjustValue'] ?? '');
            $this->printer->premiumFactorPrinter->TCIFactorAppend('不浮动原因代码', 'rateFloatFlag', $ciData['rateFloatFlag'] ?? '');
            $this->printer->premiumFactorPrinter->TCIFactorAppend('交强险业务板块类型', 'ilogbusinesstypeci', $ciData['ilogbusinesstypeci'] ?? '');


            if ($ciQueryInfo['isNewCarFlag'] ?? '') {
                $this->printer->premiumFactorPrinter->TCIFactorAppend('交强险忠诚度', 'CIRenewalType', '新');
            } else {
                if(strlen($ciQueryInfo['renewalFlag'] ?? '')){
                    $this->printer->premiumFactorPrinter->TCIFactorAppend('交强险忠诚度', 'CIRenewalType', $ciQueryInfo['renewalFlag'] ? '转' : '续');
                }
            }
        }

        //定价主信息
        if ($main = $this->getRecords(0)['main'] ?? []) {
            $this->printer->premiumFactorPrinter->ComFactorAppend('期望折扣', 'entireExpDiscount', $main['entireExpDiscount'] ?? '');
            $this->printer->premiumFactorPrinter->ComFactorAppend('交强险预期赔付率', 'ciJqecompensationRate', $main['billCtpelr'] ?? '');
            $this->printer->premiumFactorPrinter->ComFactorAppend('商业险预期赔付率', 'biNecompensationRate', $main['billComelr'] ?? '');
            //$this->printer->premiumFactorPrinter->ComFactorAppend('整单签单折扣', 'entireDiscount', $main['entireDiscount'] ?? '');
            //$this->printer->premiumFactorPrinter->ComFactorAppend('签单折扣下商业险费用率', 'billComCommission', $main['billComCommission'] ?? '');
            //$this->printer->premiumFactorPrinter->ComFactorAppend('签单折扣下商业险两率和', 'billComCor', $main['billComCor'] ?? '');
            //$this->printer->premiumFactorPrinter->ComFactorAppend('签单折扣下交强险两率和', 'billCtpCor', $main['billCtpCor'] ?? '');
            $this->printer->premiumFactorPrinter->ComFactorAppend('签单折扣下整单费用率', 'billCommission', $main['billCommission'] ?? '');
            $this->printer->premiumFactorPrinter->ComFactorAppend('签单折扣下整单两率和', 'billCor', $main['billCor'] ?? '');
            //$this->printer->premiumFactorPrinter->ComFactorAppend('签单折扣交强险预期赔付率', 'billCtpelr', $main['billCtpelr'] ?? '');
            //$this->printer->premiumFactorPrinter->ComFactorAppend('签单折扣商业险预期赔付率', 'billComelr', $main['billComelr'] ?? '');
            $this->printer->premiumFactorPrinter->ComFactorAppend('签单折扣预期赔付率', 'billElr', $main['billElr'] ?? '');

            $this->printer->premiumFactorPrinter->ComFactorAppend('光博车险承保分（整单）', 'billcomeGroup', $main['sunlightScore'] ?? '');
            $this->printer->premiumFactorPrinter->ComFactorAppend('光博车险承保分（商业险）', 'bizBillcomeGroup', $main['comSunlightScore'] ?? '');
            $this->printer->premiumFactorPrinter->ComFactorAppend('光博车险承保分（交强险）', 'efcBillcomeGroup', $main['ctpSunlightScore'] ?? '');
        }

        //险种
        if ($kinds = $this->getRecords(0)['premiumKinds'] ?? []) {
            foreach ($kinds as $kind) {
                $coverage = new PremiumCoveragePrinter();
                $coverage->coverageCode = array_search($kind['kindCode'], DBICEnums::$coverageCode);

                if ($kind['kindCode'] == 'K' and !$this->printer->isNewEnergy) {
                    $coverage->coverageCode = 'C02006';
                }
                if ($kind['kindCode'] == 'K' and $this->printer->isNewEnergy) {
                    $coverage->coverageCode = 'C12006';
                }

                $coverage->coverageName = IDockEnums::$coverageCode[$coverage->coverageCode] ?? '';
                $coverage->premium = $kind['premium'] ?? '';
                $coverage->basePremium = $kind['benchMarkPremium'] ?? '';
                $coverage->amount = $kind['amount'] ?? '';

                $this->printer->coverageListAppend($coverage);
            }
        }
        //非车信息
        if (isset($this->getRecords(0)['premiumHi'])) {
            $nonCarInfo = $this->getRecords(0)['premiumHi'];
            $this->setNonCarInfo($nonCarInfo);
        }
        return $this;
    }

    /**
     * 特约添加
     * @param $VCIResponse
     * @param $TCIResponse
     * @return void
     */
    public function setSpecialClauses($VCIResponse, $TCIResponse)
    {
        /**
         * @var $VCIResponse SpecialClausesResponse
         * @var $TCIResponse SpecialClausesResponse
         */
        if ($VCIResponse) {
            foreach ($VCIResponse->specialClausesList() as $value) {
                $specialClauses = new SpecialClausesPrinter();
                $specialClauses->clauseCode = $value['clauseCode'] ?? '';
                $specialClauses->clauseName = $value['clauseName'] ?? '';
                $specialClauses->clauseContent = $value['clauseContext'] ?? '';
                $specialClauses->riskType = 'VCI';
                $specialClauses->autoFlag = $value['autoFlag'] ?? '';
                $this->printer->specialClausesAppend($specialClauses);
            }
        }

        if ($TCIResponse) {
            foreach ($TCIResponse->specialClausesList() as $value) {
                $specialClauses = new SpecialClausesPrinter();
                $specialClauses->clauseCode = $value['clauseCode'] ?? '';
                $specialClauses->clauseName = $value['clauseName'] ?? '';
                $specialClauses->clauseContent = $value['clauseContext'] ?? '';
                $specialClauses->riskType = 'TCI';
                $specialClauses->autoFlag = $value['autoFlag'] ?? '';
                $this->printer->specialClausesAppend($specialClauses);
            }
        }
    }

    /**
     * 重复投保
     * @param $errorMsg
     * @return void
     */
    private function repeat($errorMsg)
    {
        if (preg_match('/重复投保/', $errorMsg)) {
            if (preg_match('/终保日期 ([\d -\:]+)/', $errorMsg, $matches)) {
                if ($matches[1] ?? '') {
                    $this->printer->success = false;
                    $this->printer->repeatInsuredFlg = true;
                    $this->printer->repeatMessage = $errorMsg;
                    $this->printer->repeatInsurePrinter = [
                        'ciStartData' => date('Y-m-d H:i:s', strtotime($matches[1] ?? '')),
                    ];
                    return;
                }
            }
        }

        $this->setError($errorMsg);
        $this->printer->success = false;
    }

    private function BiRepeat(): bool
    {
        if ($repeatBi = $this->getRecords(0)['reInsureItem'] ?? []) {
            $errorMsg = "商业险重复投保 保单号：" . ($repeatBi['policyNo'] ?? '') .
                ' 保险公司:' . ($repeatBi['insurerCode'] ?? '') .
                ' 车牌号：' . ($repeatBi['licensePlateNo'] ?? '') .
                ' 车架号：' . ($repeatBi['vin'] ?? '') .
                ' 发动机号' . ($repeatBi['engineNo'] ?? '') .
                ' 起保日期:' . ($repeatBi['effectiveDate'] ?? '') .
                " 终保日期: " . ($repeatBi['expireDate'] ?? '') .
                ' 签单日期：' . ($repeatBi['billDate'] ?? '') .
                ' 地区：' . ($repeatBi['insurerArea'] ?? '');


            if ($biEndData = $repeatBi['expireDate'] ?? '') {
                $biEndData = date('Y-m-d H:i:s', strtotime($biEndData));

                $this->printer->success = false;
                $this->printer->repeatInsuredFlg = true;
                $this->printer->repeatMessage = $errorMsg;
                $this->printer->repeatInsurePrinter = [
                    'biStartData' => $biEndData,
                ];

                return false;
            }
        }
        return true;
    }

    public function buildCoverage($isEnergy, array $orgList)
    {
        $orgList = array_combine(array_column($orgList, 'coverageCode'), $orgList);

        foreach ($this->printer->coverageList as &$coverage) {
            /*** @var $coverage PremiumCoveragePrinter */

            if ($isEnergy) {
                $coverage->coverageCode = 'C1' . substr($coverage->coverageCode, 2, 4);
                $coverage->coverageName = IDockEnums::$coverageCode[$coverage->coverageCode];
            }

            if (!$coverage->amount) {
                $coverage->amount = $orgList[$coverage->coverageCode]->amount ?? '';
            }

            $coverage->quantity = $orgList[$coverage->coverageCode]->quantity ?? '';
            $coverage->unitAmount = $orgList[$coverage->coverageCode]->unitAmount ?? '';
            //服务次数回写
            $coverage->serviceTimes = $orgList[$coverage->coverageCode]->serviceTimes ?? '';
        }
    }

    private function setNonCarInfo($data)
    {
        $printer = new NonCarInquiryPrinter();
        $single = new NonCarInquirySinglePrinter();
        $single->productCode = $this->productCode;
        $single->planCode = $this->planCode;
        $single->inquiryNo = $data['subpolicyno'] ?? '';
        $printer->noCarInquirySingleAppend($single);
        $printer->totalPremium = $data['trialpremium'] ?? '0';
        $this->printer->nonCarInquiryPrinter = $printer;
    }
}
